#include "ina219.h"
#include "i2c.h"

static HAL_StatusTypeDef ina219_write(uint16_t MemAddress, uint16_t value)
{
	uint8_t data[2] = {(uint8_t)(value>>8), (uint8_t)(value & 0xff)};
	return HAL_I2C_Mem_Write(&hi2c2, INA219_ADDRESS, MemAddress, I2C_MEMADD_SIZE_8BIT, data, 2, 0xff);
}

static HAL_StatusTypeDef ina219_read(uint16_t MemAddress, uint8_t *data)
{
	return HAL_I2C_Mem_Read(&hi2c2, INA219_ADDRESS, MemAddress, I2C_MEMADD_SIZE_8BIT, data, 2, 0xff);
}

void INA219_Init(void)
{
	uint16_t INA219_CONFIG_value = 	INA219_CONFIG_BVOLTAGERANGE_32V|
																	INA219_CONFIG_GAIN_2_80MV|
																	INA219_CONFIG_BADCRES_12BIT|
																	INA219_CONFIG_SADCRES_12BIT_1S_532US|
																	INA219_CONFIG_MODE_SANDBVOLT_CONTINUOUS;
	ina219_write(INA219_REG_CONFIG, INA219_CONFIG_value);
	ina219_write(INA219_REG_CALIBRATION, INA_CAL);
}

float INA219_Get_DropVoltage(void)
{
	uint8_t data0[2];
	uint16_t data1;
	float DropVoltage;
	ina219_read(INA219_REG_SHUNTVOLTAGE, data0);
	data1 = (data0[0]<<8) | (data0[1]);
	if(data1 & 0x8000)
	{
		data1 = (~data1) +1;
		DropVoltage = (float)(-data1)/1000;
		return DropVoltage;
	}
	else
	{
		DropVoltage = (float)data1/1000;
		return DropVoltage;
	}
}

float INA219_Get_BusVoltage(void)
{
	uint8_t data0[2];
	uint16_t data1;
	float BusVoltage;
	ina219_read(INA219_REG_BUSVOLTAGE, data0);
	data1 = ((data0[0]<<8) | (data0[1])) >> 3;
	BusVoltage = (float)data1 * 4 / 1000;
	return BusVoltage;
}

float INA219_Get_Power(void)
{
	uint8_t data0[2];
	uint16_t data1;
	float Power;
	ina219_read(INA219_REG_POWER, data0);
	data1 = (data0[0]<<8) | (data0[1]);
	Power = (float)data1 * 20 * 0.000244140625;
	return Power;
}

float INA219_Get_Current(void)
{
	uint8_t data0[2];
	uint16_t data1;
	float Current;
	ina219_read(INA219_REG_CURRENT, data0);
	data1 = (data0[0]<<8) | (data0[1]);
	if(data1 & 0x8000)
	{
		data1 = (~data1) +1;
		Current = (float)data1* 0.000244140625;
		return Current;
	}
	else
	{
		Current = (float)data1* 0.000244140625;
		return Current;
	}
}



